// pages/oneself/redact/redact.js
const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
const myemail = /^[0-9a-zA-Z]{3,20}\@[0-9a-zA-Z]{1,5}\.[a-z]{1,5}$/;
const format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
const app = getApp()
const connector = require('../../../utils/connector.js')
const qiniuUploader = require('../../../utils/qiniuUploader.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    fileJudge: false,//是否正在上传
    progressNum: 0,//上传进度
    tempFilePaths:'',
    fileArr:[],

  },
  //图片上传
  chatI: function () {
    var that = this;
    // console.log(connector.connector().filePath)
    let obj = {

    }
    connector.getFunc(app.conUser + connector.connector().filePath, obj, "post", app.tokens, function (res) {
      // console.log(res.data[0].upToken)
      chatI(that, res.data[0].upToken, res.data[0].domain, "head/");

    }, function (res) {
      console.log(res)

    })
  },
  //表单提交
  formSubmit: function (e) {
    var that = this
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let list = e.detail.value
    // console.log(list.name)
    if (!list.name) {
      wx.showToast({
        title: "请输入姓名",
        icon: 'none',
        duration: 1000
      })
      return false
    }
    if (!list.telephone) {
      wx.showToast({
        title: "请输入联系电话",
        icon: 'none',
        duration: 1000
      })
      return false
    } else {
      if (list.telephone.length < 11 || !myreg.test(list.telephone)) {
        wx.showToast({
          title: "联系电话输入有误",
          icon: 'none',
          duration: 1000
        })
        return false
      }
    }
    console.log(that.data.fileArr)
    if(that.data.fileArr.length > 0){
      list.picture = that.data.fileArr[0].file.imageURL
    }else{
      list.picture = that.data.user.picture
    }
    
    list.coach_id = that.data.user.coach_id
    list.sex = that.data.user.sex
    list.user_id = that.data.user.user_id
    list.school_id = that.data.user.school_id
    console.log(list)
    userCoachEdit(that,list)
    // wxUpd(that, e.detail.value)

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    let user = wx.getStorageSync("users")
    that.setData({
      user:user,
      tempFilePaths:user.picture
    })

    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
    // let user = wx.getStorageSync("myUser")
    // let name = user.wuName,
    //   phone = user.userPhone,
    //   // sex = user.sex,
    //   email = user.email;
    // if (name == '' || !name) name = ""

    // if (phone == '' || !phone) phone = ""

    // // if (sex == 1) sex = "男"
    // // else if (sex == 2) sex = "女"
    // // else sex = ""

    // if (email == '' || !email) email = ""
    // this.setData({
    //   phone: phone,
    //   name: name,
    //   // sex: sex,
    //   email: email
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {
    var that = this
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },

})



//更新个人信息
function userCoachEdit(that,obj){
  connector.getFunc(connector.connector().userCoachEdit, obj, "post", app.tokens, function (res) {
    userIfo(that)
    console.log(res)
    if (res.data.result) {
      let objs = obj
      objs.sex = that.data.user.sex
      objs.school_id = that.data.user.school_id
      objs.school = that.data.user.school

      wx.setStorageSync("users",objs)
      wx.showToast({
        title: "保存成功",
        icon: 'none',
        duration: 1000
      })
      wx.navigateBack({
        delta: 1,
      })
    }else{
      wx.showToast({
        title: "保存是失败，请重试",
        icon: 'none',
        duration: 1000
      })
    }
   
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}
// 初始化七牛相关参数
function initQiniu(tok, domain) {
  var options = {
    region: 'SCN', // 华南区
    // uptokenURL: 'https://minitest.17jxyx.com/api/v1/token/file/goods',
    uptoken: tok,
    uploadURL: 'https://up-z2.qbox.me/',
    domain: domain,
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}
//单图片上传 token:七牛上传token;types:上传文件前缀
function chatI(that, token, domain, types) {
  initQiniu(token, domain);
  // 微信 API 选文件
  wx.chooseImage({
    count: 1,
    success: function (res) {
      if (that.data.fileArr.length > 0) {
        deleteFile(that.data.fileArr[0].file.key)
      }
      let filePath = res.tempFilePaths[0];
      let obj = {
        tempFilePaths: filePath
      }
      let arr = []
      arr.push(obj)
      that.setData({
        tempFilePaths: filePath,
        fileJudge: true,
        fileArr: arr
      })
      let houzhui = filePath.lastIndexOf(".")
      let sss = filePath.slice(houzhui)
      let keys = filePath.slice(houzhui - 5, houzhui)
      let timestamp = (new Date()).getTime();
      let fileName = types + timestamp + keys + sss

      // 交给七牛上传
      qiniuUploader.upload(filePath, fileName, (ser) => {
        console.log(ser)
        let fileArr = that.data.fileArr
        fileArr[0].file = ser
        that.setData({
          fileArr: fileArr
        })
        console.log(fileArr)
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      },
        null,// 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          that.setData({
            progressNum: progress.progress
          })
          if (progress.progress == 100) {
            that.setData({
              fileJudge: false
            })
          }
        }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
//删除七牛云图片
function deleteFile(fileKey) {
  console.log(fileKey)
  let obj = {
    fileName: fileKey
  }
  connector.getFunc(app.conUser + connector.connector().fileDelete, obj, "post", app.tokens, function (res) {
    // console.log(res.data[0].upToken)
    console.log(res)

  }, function (res) {
    console.log(res)
  })
}
//获取我的信息
function userIfo(that){
  // vip_status是否购买理赔；0：未购买；1：科目一
  connector.getFunc(connector.connector().userIfo, "", "get", app.tokens, function (res) {
    console.log(res)
    if (res.statusCode == 200) {
      let identity = false
      wx.setStorageSync("userInfo",res.data.user_info)
      let myId;
      console.log(res.data.user_info.user_id)
      if(res.data.user_info.coach){
        identity = true
        myId = res.data.user_info.user_id
      }else{
        myId = res.data.user_info.pid
        identity = false
      }
      app.globalData.myId = myId
      app.globalData.identity = identity
      app.globalData.isYes = true
    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}